<?php

namespace addons\cloud_market\controller\api;

use addons\cloud_market\model\CloudMarketOrder;
use addons\cloud_market\model\CloudMarketProduct;
use addons\cloud_market\model\CloudMarketProductAgent;
use addons\cloud_market\model\CloudMarketProductToken;
use addons\cloud_market\model\CloudMarketUser;
use hiduoke\services\Random;

/**
 * 代理接口
 */
class Agent extends CloudMarketApiController
{
    protected $notApiLogin = [];
    protected $notApiCheck = ['*'];
    /**
     * @var CloudMarketProductAgent
     */
    protected $model;
    /**
     * @var CloudMarketProduct
     */
    private $Product;
    /**
     * @var CloudMarketProductToken
     */
    private $ProductToken;
    /**
     * @var CloudMarketOrder
     */
    private $OrderModel;

    public function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketProductAgent();
        $this->Product = new CloudMarketProduct();
        $this->ProductToken = new CloudMarketProductToken();
        // 平台产品
        $this->OrderModel = new CloudMarketOrder();
    }

    /*************独立系统代理******************/

    /**
     * 首页
     */
    public function index()
    {
        $this->success('请求成功');
    }

    public function getProductList()
    {

    }

    public function getAgentProduct()
    {
        $user = $this->getUser();
        $list = $this->model->where(['user_id' => $user['id'], 'status' => 0])->order('id', 'desc')->append(['product'])->select();
        return $this->success('ok', $list);
    }

    public function creteToken($agent_id = 0, $num = 0)
    {
        if ($num <= 0 || $num > 100) {
            $this->error("创建数量必须大于0小于100");
        }
        $user = $this->getUser();
        $agent = $this->model->where(['user_id' => $user['id'], 'id' => $agent_id])->findOrEmpty();
        if ($agent->isEmpty()) {
            $this->error("您没有该产品权限", [$this->model->getLastSql(), $agent]);
        }
        $new_num = $agent['number'] - $num;
        if ($new_num < 0) {
            return $this->error("剩余提货次数不足");
        }
        for ($i = 0; $i < $num; $i++) {
            $data[] = array(
                'token'      => md5(time() . Random::uuid()),
                'product_id' => $agent["product_id"],
                'type'       => $agent['token_type'],
                'channel'    => "代理",
                'user_id'    => $user['id']
            );
        }
        $this->ProductToken->saveAll($data);
        $agent->number = $new_num;
        $agent->save();
        return $this->success("OK");
    }

    public function getTokenList()
    {
        $params = request()->buildParams();
        $params['where'] = array_merge($params['where'], array(
            'user_id' => $this->getUser()['id']
        ));
        if ($params['where']['used'] == '-1') {
            unset($params['where']['used']);
        }
        $res = $this->ProductToken->getPageList([], $params);
        return $this->success($res['count'], $res['data']);
    }

    /*********平台系统代理*******************/

    //获取订单列表
    public function getOrderList()
    {
        $user = $this->getUser();
        $product_id = input('product_id', 0);
        $product = $this->Product->where(['id' => $product_id])->find();
        if (!$product) {
            return $this->error('产品不存在');
        }

        $where = ['agent_id' => $user['id'], 'aid' => $product['aid'], 'sku_id' => $product['sku_id']];

        $data = $this->OrderModel->getPageListModel()->where($where)->select();
        $count = $this->OrderModel->getPageListModel()->where($where)->count();
        $uids = [];
        foreach ($data as $key => $value) {
            $uids[] = $value['user_id'];
        }
        $users = (new CloudMarketUser())->whereIn("id", $uids)->column('username', 'id');
        foreach ($data as $key => $value) {
            $data[$key]['username'] = $users[$value['user_id']];
        }
        return $this->success($count, $data);
    }

    //获取单条订单信息
    public function getOrder($out_trade_no)
    {
        // TODO  这里未效验代理身份
        $res = $this->model->checkOrder($out_trade_no, $this->getUser()['id']);
        if ($res['code'] == -1) {
            $this->error($res['msg']);
        }
        $order = $res['data']['order'];
        $order['price'] = sprintf('%01.2f', $order['total_fee'] / 100);
        $order['username'] = (new CloudMarketUser())->where(['id' => $order['user_id']])->value('username');
        $this->success("ok", $order);
    }

    //订单代付款
    public function agentPayment($out_trade_no)
    {
        $user = $this->getUser();
        // 查询订单
        $res = $this->model->checkOrder($out_trade_no, $user['id']);
        if ($res['code'] == -1) {
            return $this->error($res['msg']);
        }
        // 发放产品
        $order = $this->OrderModel->sendAddon($out_trade_no, '');
        if (!$order) {
            return $this->error($this->OrderModel->error ?? "代支付失败，请联系管理员");
        }
        // 修改订单
        $order->agent_id = $user['id'];
        $order->save();
        // 扣除代理次数
        $agent = $res['data']['agent'];
        $agent->number = $agent['number'] - 1;
        $agent->save();
        return $this->success("ok");
    }

    public function editRemark($token_id, $remark)
    {
        $token = $this->ProductToken->where(['id' => $token_id])->findOrEmpty();
        if ($token->isEmpty()) {
            return $this->error("token不存在");
        }
        $token->remark = $remark;
        $token->save();
        return $this->success("修改成功");
    }
}
